/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.bpm.engine.impl.bpmn.behavior;

import com.je.bpm.core.model.Activity;
import com.je.bpm.core.model.CompensateEventDefinition;
import com.je.bpm.core.model.FlowElement;
import com.je.bpm.core.model.FlowElementsContainer;
import com.je.bpm.core.model.event.ThrowEvent;
import com.je.bpm.engine.delegate.DelegateExecution;
import com.je.bpm.engine.impl.bpmn.helper.ScopeUtil;
import com.je.bpm.engine.impl.context.Context;
import com.je.bpm.engine.impl.interceptor.CommandContext;
import com.je.bpm.engine.impl.persistence.entity.CompensateEventSubscriptionEntity;
import com.je.bpm.engine.impl.persistence.entity.EventSubscriptionEntityManager;
import com.je.bpm.engine.impl.util.ProcessDefinitionUtil;
import org.apache.commons.lang3.StringUtils;
import com.je.bpm.core.model.process.Process;
import java.util.ArrayList;
import java.util.List;

/**


 */
public class IntermediateThrowCompensationEventActivityBehavior extends FlowNodeActivityBehavior {

  private static final long serialVersionUID = 1L;

  protected final CompensateEventDefinition compensateEventDefinition;

  public IntermediateThrowCompensationEventActivityBehavior(CompensateEventDefinition compensateEventDefinition) {
    this.compensateEventDefinition = compensateEventDefinition;
  }

  @Override
  public void execute(DelegateExecution execution) {
    ThrowEvent throwEvent = (ThrowEvent) execution.getCurrentFlowElement();

    /*
     * From the BPMN 2.0 spec:
     *
     * The Activity to be compensated MAY be supplied.
     *
     * If an Activity is not supplied, then the compensation is broadcast to all completed Activities in
     * the current Sub- Process (if present), or the entire Process instance (if at the global level). This “throws” the compensation.
     */
    final String activityRef = compensateEventDefinition.getActivityRef();

    CommandContext commandContext = Context.getCommandContext();
    EventSubscriptionEntityManager eventSubscriptionEntityManager = commandContext.getEventSubscriptionEntityManager();

    List<CompensateEventSubscriptionEntity> eventSubscriptions = new ArrayList<CompensateEventSubscriptionEntity>();
    if (StringUtils.isNotEmpty(activityRef)) {

      // If an activity ref is provided, only that activity is compensated
      eventSubscriptions.addAll(eventSubscriptionEntityManager
          .findCompensateEventSubscriptionsByProcessInstanceIdAndActivityId(execution.getProcessInstanceId(), activityRef));

    } else {

      // If no activity ref is provided, it is broadcast to the current sub process / process instance
      Process process = ProcessDefinitionUtil.getProcess(execution.getProcessDefinitionId());

      FlowElementsContainer flowElementsContainer = null;
      if (throwEvent.getSubProcess() == null) {
        flowElementsContainer = process;
      } else {
        flowElementsContainer = throwEvent.getSubProcess();
      }

      for (FlowElement flowElement : flowElementsContainer.getFlowElements()) {
        if (flowElement instanceof Activity) {
          eventSubscriptions.addAll(eventSubscriptionEntityManager
              .findCompensateEventSubscriptionsByProcessInstanceIdAndActivityId(execution.getProcessInstanceId(), flowElement.getId()));
        }
      }

    }

    if (eventSubscriptions.isEmpty()) {
      leave(execution);
    } else {
      // TODO: implement async (waitForCompletion=false in bpmn)
      ScopeUtil.throwCompensationEvent(eventSubscriptions, execution, false);
      leave(execution);
    }
  }
}
